package com.tjetc.dao.impl;

import com.tjetc.dao.DclassesDao;
import com.tjetc.domain.Dclasses;
import com.tjetc.domain.DocNurClasses;
import com.tjetc.domain.DorClasses;
import com.tjetc.utils.Db;
import com.tjetc.utils.PageInfo;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class DclassesDaoImpl implements DclassesDao {

    @Override
    public void addDoc(Dclasses dclasses) throws SQLException {
        Db.runner0().update("insert into dclasses(did, date) values (?,?)",
                dclasses.getDid(),dclasses.getDate());
    }

    @Override
    public int getDocCount(int did) throws SQLException {
        return ((Long)Db.runner0().query("select count(id) from dclasses where did = ?",
                new ScalarHandler<>(),did)).intValue();
    }

    @Override
    public List<DocNurClasses> listClasses(String date) throws SQLException {
        return Db.runner0().query("select n.date date, GROUP_CONCAT(nid) AS nids,GROUP_CONCAT(did) AS dids\n" +
                "from nclasses n left join dclasses d\n" +
                "on n.date = d.date\n" +
                "GROUP BY n.date having n.date = ?",new BeanListHandler<>(DocNurClasses.class),date);
    }

    @Override
    public List<DorClasses> listDorClasses(PageInfo<DorClasses> pageInfo) throws SQLException {
        return Db.runner0().query("select date,GROUP_CONCAT(did) as dids from dclasses  GROUP BY date limit ?,?",
                new BeanListHandler<>(DorClasses.class),pageInfo.getStartRecord(),pageInfo.getPageSize());
    }

    @Override
    public int getCount() throws SQLException {
        return ((Long)Db.runner0().query("select count(id) from dclasses",
                new ScalarHandler<>())).intValue();
    }

    @Override
    public Dclasses findByIdandDate(int id, String dayOfWeekName) throws SQLException {
        return Db.runner0().query("select * from dclasses where did=? and date=?",
                new BeanHandler<>(Dclasses.class),id,dayOfWeekName);
    }

    @Override
    public int setqiandao(Dclasses dclasses) throws SQLException {
        return Db.runner0().update("update dclasses set status=? where id=?",
                dclasses.getStatus(),dclasses.getId());
    }

    @Override
    public void clearClasses() throws SQLException {
        Db.runner().update(Db.getConnection(),"delete from dclasses");
    }


}
